package 队列;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/implement-stack-using-queues/
 */
public class _225_用队列实现栈 {

    Queue<Integer> inQueue;
    Queue<Integer> outQueue;

    public _225_用队列实现栈() {
        inQueue = new LinkedList<>();
        outQueue = new LinkedList<>();
    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        inQueue.offer(x);
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        check();
        return inQueue.poll();
    }

    /**
     * Get the top element.
     */
    public int top() {
        check();
        return inQueue.peek();
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        return inQueue.isEmpty() && outQueue.isEmpty();
    }

    private void check() {
        if (inQueue.isEmpty()) {
            while (!outQueue.isEmpty())
                inQueue.offer(outQueue.poll());
        }
        if (inQueue.size() > 1) {
            for (int i = 0; i <= inQueue.size() - 1; i++) {
                outQueue.offer(inQueue.poll());
            }
        }
    }

}


